<?php

namespace Wxwork\Common;

use Exception;

class AESEncrypt
{
    private $key;
    private $iv;

    public function __construct($key)
    {
        $this->key = base64_decode($key . '=');
        $this->iv = substr($this->key, 0, 16);
    }

    /**
     * 解密
     * @param $encrypted
     * @param $receiveId
     * @return void
     * @throws Exception
     */
    public function decrypt($encrypted, $receiveId):string
    {
        $decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', $this->key, OPENSSL_ZERO_PADDING, $this->iv);

        //删除PKCS#7填充
        $pad = ord(substr($decrypted, -1));
        if ($pad < 1 || $pad > 32) {
            $pad = 0;
        }
        $result = substr($decrypted, 0, (strlen($decrypted) - $pad));

        if (strlen($result) < 16) {
            return '';
        }
        //拆分
        $content = substr($result, 16, strlen($result));
        $lenList = unpack('N', substr($content, 0, 4));
        $xmlLen = $lenList[1];
        $xmlContent = substr($content, 4, $xmlLen);
        $fromReceiveId = substr($content, $xmlLen + 4);


        if ($fromReceiveId != $receiveId) {
            throw new Exception('corpid 校验错误 from:'.$fromReceiveId.'---'.',loacl:'.$receiveId);
        }
        return $xmlContent;
    }
}
